import { createSlice } from '@reduxjs/toolkit'
import type { Dispatch } from '@reduxjs/toolkit'
import { http, persistence } from '@/utils'

const initialState: UserStateStore = {
  token: persistence.getToken() || '',
  userInfo: {},
  channels: []
}

const useUserStore = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setToken (state, actions) {
      state.token = actions.payload
    },
    setUserInfo (state, actions) {
      state.userInfo = actions.payload
    },
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      persistence.clearToken()
    },
    setChannels (state, actions) {
      state.channels = actions.payload
    }
  }
})

const { setToken, setUserInfo, clearUserInfo, setChannels } = useUserStore.actions

// 用户登录
const userLogin = (data: LoginForm): any => {
  return async (dispatch: Dispatch) => {
    const res = await http.post('/authorizations', data)
    dispatch(setToken(res.data.token))

    // 持久化到本地
    persistence.setToken(res.data.token as string)
  }
}

// 获取用户信息
const getUserInfo = (): any => {
  return async (dispatch: Dispatch) => {
    const res = await http.get('/user/profile')
    dispatch(setUserInfo(res.data))
  }
}

export { setToken, userLogin, getUserInfo, clearUserInfo, setChannels }
export default useUserStore.reducer